﻿using CRM.Models;
using System.Linq;
using CRM.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using System;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using CRM.ViewModels.User;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Identity;
using CRM.Enums;
using Z.EntityFramework.Plus;
using System.Transactions;

namespace CRM.Controllers.UserManage
{
    [Route("api/[controller]")]
    [ApiController]
    public class RuleTemplateController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> userManager;
        private readonly ILogger<RuleTemplateController> logger;

        public RuleTemplateController(MyDbContext dbContext,ILogger<RuleTemplateController> logger,UserManager<User> userManager)
        {
            _dbContext = dbContext;
            this.logger = logger;
            this.userManager = userManager;

        }


        [HttpGet("[Action]")]
        public async Task<ResultStruct> GetList([FromQuery] string name, [FromQuery] States? state)
        {
            var u = userManager.GetUserAsync(User).Result;
            IQueryable<RuleTemplate> sqlQuery = _dbContext.RuleTemplate.Where(i => i.CompanyId == u.CompanyId).Where(i => i.OemId == u.OemId);

            if (state.HasValue)
            {
                sqlQuery = sqlQuery.Where(i => i.State == state);
            }

            if (!string.IsNullOrEmpty(name))
            {
                sqlQuery = sqlQuery.Where(i => i.Name == name);
            }

            var data = await sqlQuery.OrderBy(i => i.State).ThenByDescending(i => i.Id).ToPaginateAsync(Request);
            return Success(data);
        }

        [HttpPost("[Action]")]
        public async Task<ResultStruct> GetInfo(GetDataId RequestData)
        {
            var row = await _dbContext.RuleTemplate.Where(m => m.Id == RequestData.Id).FirstOrDefaultAsync();
            return row == null ? Error() : Success(data: row);
        }


        [HttpPost("[Action]")]
        public async Task<ResultStruct> SubAddInfo(JObject jsonData)
        {
            _ = Enum.TryParse(jsonData["state"].ToString(), out States states);
            var u = userManager.GetUserAsync(User).Result;
            RuleTemplate model = new()
            {
                Name = Convert.ToString(jsonData["name"]),
                State = states,
                Remark = Convert.ToString(jsonData["remark"]),
                CompanyId = u.CompanyId,
                OemId = u.OemId,
                Sort = -Helper.GetNowTimeStamp(),
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };
            //复制当前公司权限

            await _dbContext.RuleTemplate.AddAsync(model);
            await _dbContext.SaveChangesAsync();

            return Success();
        }


        [HttpPost("[Action]")]
        public async Task<ResultStruct> SubEditInfo(JObject jsonData)
        {
            var id = Convert.ToInt32(jsonData["id"]);
            var row = await _dbContext.RuleTemplate.FindAsync(id);
            if (row == null) return Error(message: "无权操作");
            row.Name = Convert.ToString(jsonData["name"]);
            row.Remark = Convert.ToString(jsonData["remark"]);
            _ = Enum.TryParse(jsonData["state"].ToString(), out States states);
            row.State = states;
            await _dbContext.SaveChangesAsync();
            return Success();
        }
        [HttpPost("[Action]")]
        public async Task<ResultStruct> delInfo(GetDataId RequestData)
        {
            var row = await _dbContext.RuleTemplate.FindAsync(RequestData.Id);
            if (row == null) return Error(message: "无权操作");
            //查找引用当前权限模板公司用户
            var ret = await _dbContext.Users.Where(m => m.RuleId == RequestData.Id).FirstOrDefaultAsync();
            if (ret != null) return Error(message: "当前权限组下存在用户，禁止删除。");

            _dbContext.RuleTemplate.Remove(row);
            await _dbContext.SaveChangesAsync();
            return Success();
        }

        /// <summary>
        /// 获取权限模版权限信息
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        [HttpPost("[Action]")]
        public async Task<ResultStruct> GetAuthItems(GetDataId RequestData) {
            RuleTemplate RuleTemplateInfo = await _dbContext.RuleTemplate.Where(m => m.Id == RequestData.Id).FirstOrDefaultAsync();
            var All = _dbContext.Menus.OrderBy(i => i.ParentId).ThenBy(i => i.Sort).ToArray().Where(m => User.HasPermission(m)).ToList();
            All.ForEach(m => m.Has = RuleTemplateInfo.HasPermission(m));
            var ret = All.GetAuthItem(logger);
            return ret.IsNull()?Error(ret):Success(ret);
        }

        /// <summary>
        /// 提交权限模版提交权限信息
        /// </summary>
        /// <param name="authInfo"></param>
        /// <returns></returns>
        [HttpPost("[Action]")]
        public ResultStruct SubAuthInfo(AuthInfo authInfo) {
            RuleTemplate ruleTemplate = new();
            ruleTemplate.Id = authInfo.ID;
            var edt = _dbContext.Attach(ruleTemplate);
            edt.State = EntityState.Unchanged;
            ruleTemplate.SetData(authInfo, edt);
            _dbContext.SaveChanges();
            //RuleTemplateService RuleTemplateService = new(_dbContext);
            //RuleTemplateService.UpdatePermission(ruleTemplate, authInfo.ID);


            return Success();
        }


        /// <summary>
        /// 获取用户权限信息
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        [HttpPost("[Action]")]
        public async Task<ResultStruct> GetUserAuthItems(GetDataId RequestData)
        {
            List<UserClaim> userClaims =await _dbContext.UserClaims.Where(m => m.UserId == RequestData.Id).ToListAsync();
            var All = _dbContext.Menus.OrderBy(i => i.ParentId).ThenBy(i => i.Sort).ToArray().Where(m => User.HasPermission(m)).ToList();
            All.ForEach(m => m.Has = userClaims.HasPermission(m));
            var ret = All.GetAuthItem(logger);
            return ret.IsNull() ? Error(ret) : Success(ret);
        }

        /// <summary>
        /// 提交用户权限信息
        /// </summary>
        /// <param name="authInfo"></param>
        /// <returns></returns>
        [HttpPost("[Action]")]
        public async Task<ResultStruct> SubUserAuthInfo(AuthInfo authInfo)
        {
            RuleTemplate ruleTemplate = new();
            //ruleTemplate.Id = authInfo.ID;
            //var edt = _dbContext.Attach(ruleTemplate);
            //edt.State = EntityState.Unchanged;
            ruleTemplate.SetData(authInfo, null);
            using (var scope = new CommittableTransaction())//创建事务
            {
                try
                {
                    //删除 userClaims
                    _dbContext.UserClaims.Where(u => u.UserId == authInfo.ID).Delete();

                    //重新添加绑定关系
                    User UserInfo = _dbContext.Users.Where(m => m.Id == authInfo.ID).FirstOrDefault(); ;
                    var AddAuthRet = await userManager.AddClaimsAsync(UserInfo, ruleTemplate.GetClaims(UserInfo.OemId));

                    scope.Commit();//重点，事务的提交
                }
                catch (Exception e)
                {
                    //scope.Rollback();
                    scope.Dispose();
                    return Error(e.Message);
                }
            }

            return Success();
        }
    }
}
